<template>
  <div class="ios">
    <div class="w-full h-[77px] flex justify-center items-center flex-col">
      <div class="text-[14px] font-bold">{{ Info.name }}</div>
      <div class="mt-[5px] text-[10px]">由{{ Info.brand }}承保</div>
    </div>
    <div>
      <insureTitle title="保险日期"></insureTitle>
      <div class="p-[15px]">
        <div class="flex items-center justify-between" @click="openPicker(0)">
          <div class="flex text-[14px]">
            <div>生效日期</div>
            <div class="ml-[50px]">
              {{
                startTimer
                  ? startTimer + " 00:00:00"
                  : year + "-" + month + "-" + strDate + " 00:00:00"
              }}
            </div>
          </div>
          <div>
            <img :src="getAssetsFile('home/date.png')" class="w-[14px] h-[14px]" />
          </div>
        </div>
        <div class="border-b border-[#ECECEC] my-[15px]"></div>
        <div class="flex items-center justify-between" @click="openPicker(1)">
          <div class="flex text-[14px]">
            <div>结束日期</div>
            <div class="ml-[50px]">
              {{ endTimer ? endTimer + " 23:59:59" : "请选择结束时间" }}
            </div>
          </div>
          <div>
            <img :src="getAssetsFile('home/date.png')" class="w-[14px] h-[14px]" />
          </div>
        </div>
        <div class="border-b border-[#ECECEC] my-[15px]"></div>
        <div class="flex items-center justify-between">
          <div class="flex text-[14px]">
            <div>有效天数</div>
            <div class="ml-[50px]">
              <input type="number" v-model="days" @input="daysInput" />
              <!-- {{ days ? days : "0" }} -->
            </div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <van-form ref="formRef" label-width="98">
        <van-cell-group inset>
          <div>
            <insureTitle title="投保人信息"></insureTitle>
            <tbrxx
              ref="tbrxxRef"
              :infoTbrxx="infoTbrxx"
              :Info="Info"
              :edit="edit"
            ></tbrxx>
          </div>
          <!-- <div v-if="route.query.id !== '1'">
            <insureTitle title="附加被保人"></insureTitle>
            <fjInsured :Info="Info" ref="fjInsuredRef" :edit="edit"></fjInsured>
          </div> -->
          <div>
            <insureTitle title="标的要素"></insureTitle>
            <ys
              ref="ysRef"
              :Info="param"
              :edit="edit"
              @pickerConfirm="pickerConfirm"
              @inputChange="inputChange"
            ></ys>
          </div>
          <div>
            <insureTitle title="保险责任"></insureTitle>
            <responsibility
              :duty="Info.duty"
              :start_time="startTimer"
              :end_time="endTimer"
              ref="responsibilityRef"
              :edit="edit"
              :param="param"
              :fananCost="param.fananCost"
              :personCost="personCost"
              @onConfirm="change"
              @inputChange1="inputChange1"
            ></responsibility>
          </div>
          <!-- <div>
            <insureTitle title="资料文件"></insureTitle>
            <upload ref="uploadRef" :edit="edit"></upload>
          </div> -->
        </van-cell-group>
        <div class="flex px-[15px] pb-[15px]" v-if="edit == true || routeType == '3'">
          <div @click="checked = !checked" class="mt-[2px]">
            <img
              v-if="checked"
              :src="getAssetsFile('insure/active.png')"
              class="min-w-[14px] h-[14px]"
            />
            <img
              v-else
              :src="getAssetsFile('insure/noactive.png')"
              class="min-w-[14px] h-[14px]"
            />
          </div>
          <div class="ml-[10px] text-[14px]">
            购买前，请仔细阅读<span class="text-[#EF6800]" @click="clickPush(1)"
              >《投保须知》</span
            ><span class="text-[#EF6800]" @click="clickPush(2)">《特别约定》</span
            ><span class="text-[#EF6800]" @click="clickPush(3)">《产品条款》</span
            ><span class="text-[#EF6800]" @click="clickPush(4)">《保单样本》</span>
          </div>
        </div>
        <!-- 填写投保信息 -->
        <div class="w-full h-[60px] flex items-center ios" v-if="routeType == '3'">
          <div
            class="flex-1 text-[#f3a140] font-bold flex justify-center items-center h-[60px] text-[20px]"
          >
            ￥{{ cost.toFixed(2) }}
          </div>
          <div class="flex items-center justify-center px-[15px] flex-1" @click="share">
            <img :src="getAssetsFile('home/share.png')" class="w-[16px] h-[16px]" />
            <div class="text-[14px] text-[#636363] ml-[5px]">分享</div>
          </div>
          <div
            @click="openNotice()"
            class="h-[60px] flex-1 flex justify-center items-center text-white"
            style="background: linear-gradient(180deg, #f3a140 0%, #f38e40 100%)"
          >
            立即投保
          </div>
        </div>

        <!-- 修改投保信息 -->
        <div
          class="w-full h-[60px] flex items-center ios"
          v-if="route.query.order_id && routeType == '1'"
        >
          <div
            class="flex-1 text-[#f3a140] font-bold flex justify-center items-center h-[60px] text-[20px]"
          >
            ￥{{ cost.toFixed(2) }}
          </div>
          <div class="flex items-center justify-center mx-[15px] flex-1" @click="Edit">
            <div class="text-[#636363] ml-[5px]">修改</div>
          </div>
          <div
            @click="pay"
            class="h-[60px] flex-1 flex justify-center items-center text-white"
            style="background: linear-gradient(180deg, #f3a140 0%, #f38e40 100%)"
          >
            <span>{{ edit ? "提交保单" : "确认支付" }}</span>
          </div>
        </div>
      </van-form>
    </div>
    <van-popup v-model:show="showBottom" position="bottom" safe-area-inset-bottom>
      <van-date-picker
        :filter="filter"
        title="选择日期"
        v-model="currentDate"
        @confirm="pickerConfirm"
        @change="pickerChnage"
        @cancel="showBottom = false"
      />
    </van-popup>
  </div>
  <!-- 条款 -->
  <div>
    <van-popup round v-model:show="articleShow" position="center" safe-area-inset-bottom>
      <div
        v-for="item in Info.doc"
        class="rounded-[10px] p-[10px]"
        @click="clickArticle(item, 3)"
      >
        <div class="text-[14px] text-blue-300">{{ item.title }}</div>
      </div>
    </van-popup>
  </div>
  <!-- 遮阳罩 -->
  <div>
    <van-overlay :show="overlayShow" />
  </div>
  <!-- 投保须知弹窗 -->
  <div>
    <van-popup
      round
      v-model:show="noticeShow"
      position="center"
      safe-area-inset-bottom
      :close-on-click-overlay="false"
    >
      <div class="rounded-[10px] px-[10px] pt-[10px] pb-[60px] h-[400px] relative">
        <div class="flex justify-center items-centern font-bold text-[20px]">
          投保须知
        </div>
        <div class="" v-html="Info.notice"></div>
        <div class="bg-white flex justify-center items-center sticky bottom-0 py-[10px]">
          <van-button type="primary" :disabled="dialogTime > 0" @click="sumbit"
            >我已全部阅读<span v-if="dialogTime">（{{ dialogTime }}s）</span>
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script setup lang="ts">
import insureTitle from "./insureTitle.vue"; //标题
import tbrxx from "./tbrxx.vue"; //投保人信息
import responsibility from "./responsibility.vue"; //保险责任
import upload from "./upload.vue";
import fjInsured from "./fjInsured.vue"; //附加被保人
import getAssetsFile from "@/utils/getImageurl";
import { showToast, type FormInstance } from "vant";
import { ref, computed, reactive } from "vue";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
import ys from "./ys.vue"; //标的要素
import { getInsureInfo, addOrder, orderDetail, submitApi } from "@/utils/api";
import { getTime, setDate } from '@/utils/tools'
import * as rrweb from "rrweb";
import { listenerHandler } from "_@rrweb_types@2.0.0-alpha.16@@rrweb/types";
const router = useRouter();
const route = useRoute();
const showBottom = ref(false);
const type = ref(0);
const routeType = ref(""); //1是去支付，2是查看详情 3是投保
const startTimer = ref("");
const endTimer = ref("");
const year = ref<any>();
const month = ref<any>();
const strDate = ref<any>();
const articleShow = ref(false);
const personCost = ref<number>(0)
const overlayShow = ref(false);
const cost = ref(0);
const dialogTime = ref(5);
const filterYear = ref();
const filterMonth = ref();
const filterDay = ref();
const checked = ref(false); //投保须知选中
const formRef = ref<FormInstance>();
const edit = ref(true); //是否可以修改
const param = reactive<sumbitType>({
  id: "",
  bx_id: "", //保险id
  start_time: "", //开始时间
  end_time: "", //结束时间
  insure: {
    name: "", //投保人名称
    card_type: "", //投保人证件类型
    card_no: "", //投保人证件号
    contact: "", //投保人联系人
    contact_mobile: "", //投保人联系人手机号
    mailbox: "",
    address: ""
  },
  insured: [],
  treetop: {
    name: "",
    address: "",
    age: "",
    code: "",
    start_date: "",
    end_date: "",
    classify: "室内装修",
    num: "",
    room_no: "",
  },
  duty: [] as any[],
  annex: [],
  user: [],
  card_type: "",
  add_price: 0,
  is_show: "1",
  fananCost: 0,
  mark:[] as any
});
//获取投保页信息
const Info = ref({} as any);
const infoTbrxx = reactive<infoTbrxxType>({
  name: "",
  card_type: "",
  card_no: "",
  contact: "",
  contact_mobile: "",
  mailbox: "",
  insure_type: "",
  address: ""
});
const noticeShow = ref(false); //投保须知弹窗
// const fananCost = ref("");
const tbrxxRef = ref<InstanceType<typeof tbrxx>>();
const fjInsuredRef = ref<InstanceType<typeof fjInsured>>();
const ysRef = ref<InstanceType<typeof ys>>();
const responsibilityRef = ref<InstanceType<typeof responsibility>>();
const uploadRef = ref<InstanceType<typeof upload>>();
const days = ref(0);
const currentDate = computed(() => {
  return getDate();
});
onBeforeRouteLeave(() => {
  if (!route.query.order_id) {
    setSession();
  }
  if (stopFun) {
    stopFun();
  }
  param.mark = [];
});
let stopFun: listenerHandler | undefined;
//开始录制
const player = () => {
  let stop = rrweb.record({
    emit(event: any) {
      if(param.mark)
      param.mark.push(event);
    },
  });
  stopFun = stop;
};
const Edit = () => {
  edit.value = true;
  player();
}
const daysInput = () => {

  // getTime(startTimer.value)
  param.treetop["start_date"] = startTimer.value;
  let st = getTime(startTimer.value)
  let end = st + (days.value - 1) * 3600 * 1000 * 24
  endTimer.value = setDate(end)
  param.treetop["end_date"] = endTimer.value;
  countAge(param.treetop["start_date"], param.treetop["end_date"]); //计算工期
}

const openNotice = () => {
  if (!checked.value) return showToast("请阅读协议");
  noticeShow.value = true;
  countDown();
};
//缓存数据
const setSession = () => {
  setParam();
  sessionStorage.setItem("insure", JSON.stringify(param));
};
//倒计时
const countDown = () => {
  let t = setInterval(() => {
    if (dialogTime.value > 0) {
      dialogTime.value--;
    }

    if (dialogTime.value <= 0) {
      clearInterval(t);
    }
  }, 1000);
};
//获取缓存数据
const getSession = () => {
  if (sessionStorage.getItem("insure")) {
    let key: keyof sumbitType;
    for (key in param) {
      param[key] = JSON.parse(sessionStorage.getItem("insure") as string)[key];
    }
    let infokey: keyof infoTbrxxType;
    for (infokey in infoTbrxx) {
      infoTbrxx[infokey] = param.insure[infokey] as string;
    }
    if (param.start_time && param.end_time) {
      startTimer.value = param.start_time;
      endTimer.value = param.end_time;
      let star = new Date(startTimer.value).getTime();
      let end = new Date(endTimer.value).getTime();
      days.value = (end - star) / (1000 * 3600 * 24) + 1;

      countCost(param.fananCost as number);

    }
  }
};
const inputChange = (end: any, v: number) => {
  endTimer.value = end;
  //Info.value.treetop["end_date"] = end;
  days.value = v;

  countCost(param.fananCost as number);
};
//加费输入框计算
const inputChange1 = () => {
  countCost(param.fananCost as number);
};
const change = (value: Array<any>) => {
  param.fananCost = value[0]; //方案保费
  if (days.value < 7) {
    showToast("投保时间最少为7天");
  } else {
    countCost(param.fananCost as number);
  }
};
const clickPush = (type: number) => {
  // let param = {
  //   type: type,
  //   id: Info.value.id,
  // };
  if (type == 3) {
    articleShow.value = true;
    return;
  }
  router.push(`/h5/article?types=${type}&id=${route.query.id}`);
};
//计算保费
const countCost = (price: number) => {
  let rate = "0";
  switch (String(price)) {
    case "330.00":
      rate = "10";
      break;
    case "440.00":
      rate = "15";
      break;
    case "550.00":
      rate = "20";
      break;
  }
  // if (days.value < 7) {
  //   showToast("投保时间最少为7天");
  //   return;
  // }
  // console.log(price);

  cost.value =
    Number(price) + (days.value - 7) * Number(rate) + Number(param.add_price);
  personCost.value = Number(price) + (days.value - 7) * Number(rate);
};
//产品条款
const clickArticle = (item: any, type: number) => {
  router.push(`/h5/article?types=${type}&id=${item.id}`);
};
//过滤时间
const filter = (type: any, options: any) => {
  if (type == "year") {
    return options.filter(
      (option: any) => Number(option.value) >= new Date().getFullYear()
    );
  }
  if (type == "day") {
    return filterDayDate(options);
  }
  if (type == "month") {
    return filterMonthDate(options);
  }

  return options;
};
//过滤月份
const filterMonthDate = (options: any) => {
  if (filterYear.value == new Date().getFullYear()) {
    return options.filter(
      (option: any) => Number(option.value) >= new Date().getMonth() + 1
    );
  } else {
    return options;
  }
};
//过滤天数
const filterDayDate = (options: any) => {
  if (
    filterMonth.value == new Date().getMonth() + 1 &&
    filterYear.value == new Date().getFullYear()
  ) {
    return options.filter(
      (option: any) => Number(option.value) >= new Date().getDate() + 1
    );
  } else {
    return options;
  }
};
const pickerChnage = (value: any) => {
  filterYear.value = value.selectedValues[0];
  filterMonth.value = value.selectedValues[1];
  filterDay.value = value.selectedValues[2];
};
//获取当前时间
const getDate = () => {
  let date = new Date();
  filterYear.value = new Date().getFullYear();
  filterMonth.value = date.getMonth() + 1;
  year.value = date.getFullYear(); //获取完整的年份(4位)
  month.value = date.getMonth() + 1; //获取当前月份(0-11,0代表1月)
  month.value = month.value < 10 ? "0" + month.value : month.value;
  strDate.value = date.getDate() + 1; // 获取当前日(1-31)
  strDate.value = strDate.value < 10 ? "0" + strDate.value : strDate.value;
  routeType.value = route.query.type as string;

  let data = [`${year.value}`, `${month.value}`, `${strDate.value}`];
  // startTimer.value = year.value + "-" + month.value + "-" + strDate.value;
  // Info.value.treetop["start_date"] = startTimer.value;
  return data;
};

//获取投保页面信息
const getInfo = async () => {
  getDate();
  if (route.query.id && !route.query.order_id) {
    const res = await getInsureInfo({ id: route.query.id });

    Info.value = res.msg;
    Info.value["treetop"] = {};
    startTimer.value = getDate()[0] + "-" + getDate()[1] + "-" + getDate()[2];
    param.treetop["start_date"] = startTimer.value;
    getSession();
    if (!param.fananCost) {
      param.fananCost = res.msg.duty[0].price;
    }
    player()
  } else {
    sessionStorage.removeItem("insure");
    //详情页
    const res = await orderDetail({ id: route.query.order_id });
    edit.value = false;
    let key: keyof infoTbrxxType;
    for (key in infoTbrxx) {
      infoTbrxx[key] = res.msg.insure[key];
    }
    // infoTbrxx.name = res.msg.bx_info.name;

    Info.value = res.msg;
    Info.value.name = res.msg.bx_info.name;
    Info.value.brand = res.msg.bx_info.brand;
    Info.value.doc = res.msg.bx_info.doc
    startTimer.value = res.msg.start_time;
    // Info.value.treetop["start_date"] = startTimer.value;
    endTimer.value = res.msg.end_time;
    // Info.value.treetop["end_date"] = endTimer.value;
    param.add_price = Number(res.msg.add_price);
    param.treetop = res.msg.treetop;
    param.mark = res.msg.mark;
    cost.value = Number(res.msg.total_price);
    countDays();
    let star = new Date(startTimer.value).getTime();
    let end = new Date(endTimer.value).getTime();
    days.value = (end - star) / (1000 * 3600 * 24) + 1;
    // fananCost.value = String(cost.value - Number(res.msg.add_price));
    param.fananCost = Number(res.msg.total_price) - Number(res.msg.add_price);
    personCost.value = Number(res.msg.total_price) - Number(res.msg.add_price)
  }
};
getInfo();
//计算天数
const countDays = () => {
  let st = new Date(startTimer.value).getTime();
  let end = new Date(endTimer.value).getTime();
  days.value = (end - st + 1000 * 60 * 60 * 24) / (1000 * 60 * 60 * 24);
};
const pickerConfirm = (res: any, t: number) => {
  if (t) {
    type.value = t;
  }

  if (type.value) {
    //选择结束时间
    endTimer.value =
      res.selectedValues[0] +
      "-" +
      res.selectedValues[1] +
      "-" +
      res.selectedValues[2];
    param.treetop["end_date"] = endTimer.value;
  } else {
    //选择开始时间
    startTimer.value =
      res.selectedValues[0] +
      "-" +
      res.selectedValues[1] +
      "-" +
      res.selectedValues[2];


    param.treetop["start_date"] = startTimer.value;
    let star = startTimer.value + " 00:00:00";

let date1 = new Date(star).getTime();

let time = date1 - 1000 * 3600 * 24 + days.value * 1000 * 3600 * 24;

endTimer.value = timestampToTime(time);

  }
  showBottom.value = false;
  countAge(param.treetop["start_date"], param.treetop["end_date"]);
  countDays();
  countCost(param.fananCost as number);

};
// 时间戳：1637244864707
/* 时间戳转换为时间 */
const timestampToTime = (timestamp: any) => {
  timestamp = timestamp ? timestamp : null;
  let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let Y: any, M: any, D: any;
  Y = date.getFullYear();
  M = date.getMonth() + 1;
  M = M < 10 ? "0" + M : M;
  D = date.getDate();
  D = D < 10 ? "0" + D : D;

  return Y + "-" + M + "-" + D;
};
//计算工期
const countAge = (st: any, end: any) => {
  if (!end) {
    end = getDate()[0] + "-" + getDate()[1] + "-" + getDate()[2];
  }

  let start_date = st + " 00:00:00";
  let end_data = end + " 00:00:00";
  let start_time = new Date(start_date).getTime(); //开始时间戳
  let end_time = new Date(end_data).getTime();

  if (end_time < start_time) {
    param.treetop["age"] = "0";
    return;
  }
  param.treetop["age"] = String(
    (end_time - start_time + 1000 * 60 * 60 * 24) / (1000 * 60 * 60 * 24)
  );

};
const openPicker = (i: number) => {
  //i 0是开始时间 1是结束数据
  if (routeType.value == "2" || edit.value == false) return;

  type.value = i;
  showBottom.value = true;
};
const setParam = () => {
  param.bx_id = route.query.id as string;
  let tbrxxKey: keyof insureType;
  for (tbrxxKey in param.insure) {
    param.insure[tbrxxKey] = tbrxxRef.value?.Info[tbrxxKey] as string;
  }
  let treekey: keyof treetopType;
  for (treekey in param.treetop) {
    param.treetop[treekey] = ysRef.value?.Info[treekey];
  }

  param.insured = fjInsuredRef.value?.list;
  param.start_time = startTimer.value;
  param.end_time = endTimer.value;

  param.duty = responsibilityRef.value?.list;
  param.annex = uploadRef.value?.uploadList;
};
const sumbit = () => {
 if (!checked.value) return showToast("请阅读协议");
  // if (days.value < 7) return showToast("投保时间最少7天");
  noticeShow.value = false;
  formRef.value
    ?.validate()
    .then(async (_) => {
      countCost(param.fananCost as number);
      setParam();
      if (param.treetop.address) {
        if (param.treetop.address.length < 5) {

          showToast("工地地址不得少于五个字");
          return
        }
      }
      if (stopFun) {
        stopFun()
      }
      const res = await addOrder(param);
      if (res.code == 1) {
        sessionStorage.removeItem("insure");
        showToast("提交成功");
        let order_id = res.msg;

        setTimeout(() => {
          edit.value = false;
          router.replace(
            `/h5/insure?id=${param.bx_id}&order_id=${order_id}&type=1`
          );
          routeType.value = "1";
          route.query.order_id = res.msg;
          getInfo();
        }, 500);
      } else {
        showToast(res.msg);
      }
    })
    .catch((_) => { });
};
//支付
const pay = async () => {
  if (edit.value) {
    //提交保单
    sumbit();
  } else {
    // 支付
    overlayShow.value = true;
    const res = await submitApi({ id: route.query.order_id });
    if (res.code == 1) {
      window.location.href = res.msg;
    } else {
      showToast(res.msg);
    }
    overlayShow.value = false;
  }
};
const share = () => {
  router.push("/h5/insure/share?id=" + Info.value.id);
};
</script>
<style scoped lang="scss">
:deep(.van-cell-group--inset) {
  margin: 0 !important;
}

:deep(.van-field__control::-webkit-input-placeholder) {
  color: #9b9da9;
}

.ios {
  padding-bottom: constant(safe-area-inset-bottom);
}
</style>
